# main.py
# !/usr/bin/python3.6
# -*- coding: utf-8 -*-
# @Time    : 2024/11/26 11:47
# @Author  : zmz,whx
# @File    : main.py
# @function: 主函数
# @Software: PyCharm

import PySimpleGUI as sg

import Investment_payback_period as _ipp
import ai_talk  # 导入AI对话界面布局
import breakeven_analysis as _break
import capital_equivalent as _capital
import excel_import as _excel
import help
import internal_rate_of_return as _irr
import net_present_value as _npv
import public_data as _pub
import sensitivity_analysis as _sens

# 定义自定义主题
default_theme_name = sg.theme()
default_theme = sg.LOOK_AND_FEEL_TABLE[default_theme_name].copy()
default_theme["FONT"] = ("Microsoft YaHei", 16)
# 添加自定义主题
sg.theme_add_new('ModifiedDefaultTheme', default_theme)
# 使用自定义主题
# sg.theme('ModifiedDefaultTheme')

# 主窗口布局
layout = [
    [sg.Menu([['文件', ['导入Excel', '退出']], ['帮助', ['关于']]])],
    [sg.TabGroup([[sg.Tab("基础数据", _pub.pub_layout),
                   sg.Tab("敏感性分析", _sens.layout),
                   sg.Tab("盈亏平衡分析", _break.layout),
                   sg.Tab("资金的等值计算", _capital.layout),
                   sg.Tab("净现值计算", _npv.layout),
                   sg.Tab("IRR计算", _irr.irr_layout),
                   sg.Tab("方案比选", _irr.com_layout),
                   sg.Tab("动态投资回收期", _ipp.dynamics_layout),
                   sg.Tab("差额投资回收期", _ipp.diff_layout),
                   sg.Tab("AI对话", ai_talk.ai_dialog_layout),  # 添加AI对话界面选项卡
                   # sg.Tab("数据处理", _convet.layout),
                   ]], key='-TAB_GROUP-', pad=(20, 15))],  # TabGroup用于多选项卡布局
    [sg.Text("运行日志", size=(100, 1), key='-LOG_LABEL-', visible=True)],
    [sg.Button("清空", size=(10, 1), key='-CLEAR_LOG-', visible=True)],
    [sg.Multiline(size=(132, 10), key='-DEBUG_OUTPUT-', reroute_cprint=True, visible=True)]
]


def update_excel_data(excel_data):
    _irr.update_excel_data(excel_data)
    _npv.update_excel_data(excel_data)


def update_pub_data(pub_data):
    _irr.update_pub_data(pub_data)
    _npv.update_pub_data(pub_data)
    _ipp.update_pub_data(pub_data)

# 主程序
def main():
    w_title = "[2024级工程管理专业A班]-[第五组-欢乐斗地组]-[组员：郑剑平、吴海欣、植美炤、何国静、吴晔琼、梁静]"
    # 创建窗口
    window = sg.Window(w_title, layout, finalize=True, size=(1024, 768))  # finalize=True确保窗口在显示前已经完全初始化

    # 绑定 public_data 中的事件
    _pub.bind_events(window)
    update_pub_data('')

    while True:
        event, values = window.read()
        if event == sg.WINDOW_CLOSED or event == "退出":
            break

        elif event == "关于":
            help.help_info()

        elif event == 'PUB_I_INPUT-_KEY_RELEASE' or event == 'PUB_R_INPUT-_KEY_RELEASE' or event == 'PUB_MARR_INPUT-_KEY_RELEASE':
            # 获取 InputText 的值
            _pub.read_pub_values(values)
            update_pub_data(values)

        elif event == "INAPV_BTN":
            _capital.capital_equivalence_handle(values)

        elif event == "计算NPV":
            _npv.Net_Present_Value_Handle(values)

        elif event == '计算 IRR':
            _irr.Internal_Rate_of_Return_Handle(values)

        elif event == '进行比选':
            if _irr.sheme_comparison_handle(values):
                continue

        elif event == '计算动态投资回收期':
            _ipp.dynamics_Investment_handle(values)

        elif event == '计算差额投资回收期':
            _ipp.diff_Investment_handle(window, values)

        elif event == '盈亏平衡分析':
            _break.break_handle(window, values)

        elif event == "计算敏感性分析":
            _sens.Sensitivity_nalysis_handle(window, values)

        elif event == "转换并输出":
            input_data = values['-INPUT-'].splitlines()
            output_data = ", ".join(input_data)
            window['-OUTPUT-'].update(output_data)

        elif event == '清空':
            window['-DEBUG_OUTPUT-'].update('')

        elif event == '导入Excel':
            file_path = sg.popup_get_file('请选择Excel文件', file_types=(("Excel Files", "*.xlsx"),))
            if file_path:
                try:
                    data = _excel.import_excel(file_path)
                    sg.cprint("数据导入成功！")
                    # 打印 data 的前几行
                    print(data.head())
                    grouped_data = data.groupby('solution')
                    # 定义特定顺序
                    # order = ['Q1Z', 'Q1D', 'Q2Z', 'Q2D']
                    # 按特定顺序重新索引分组结果
                    # grouped_data_ordered = {key: grouped_data.get_group(key) for key in order if key in grouped_data.groups}
                    sg.cprint(f"按方案'solution'列分组的数据行数:\n{grouped_data.size()}")
                    update_excel_data(data)
                    update_pub_data('')
                except Exception as e:
                    sg.cprint(f"数据导入失败: {e}")
            else:
                sg.cprint("请选择一个有效的Excel文件")

        # 处理AI对话事件
        elif event == '发送':
            ai_talk.chat_with_ai(window, values)

        # 处理清空对话事件
        elif event == '清空对话':
            ai_talk.reset_dialog(window)

        # 监听 TabGroup 事件
        elif event == '-TAB_GROUP-':
            current_tab = values['-TAB_GROUP-'][0]  # 获取当前选中的选项卡名称
            print(f"当前选中的选项卡: {current_tab}")  # 调试信息
            if current_tab == 'AI对话':
                window['-LOG_LABEL-'].update(visible=False)
                window['-CLEAR_LOG-'].update(visible=False)
                window['-DEBUG_OUTPUT-'].update(visible=False)
            else:
                window['-LOG_LABEL-'].update(visible=True)
                window['-CLEAR_LOG-'].update(visible=True)
                window['-DEBUG_OUTPUT-'].update(visible=True)

    window.close()

# 启动函数
if __name__ == "__main__":
    main()
